// @flow
import React, { Component } from 'react'
import styles from './HistoryFre.css'
import { Spin, Button, message, Popover, Checkbox, Select, DatePicker } from 'antd'
// import R from 'ramda'
import moment from 'moment'
import DynamicLineLiandong from 'components/DynamicLineLiandong'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
const Option = Select.Option
const CheckboxGroup = Checkbox.Group
const { RangePicker } = DatePicker
type Props = {
  deviceData: Object
}

type States = {
  loading: boolean,
  chartData: Array<any>,
  channelData: Array<Object>,
  channelIdSpeed: Object,
  channelIdDeric: Array<string>,
  channelIds: Array<string>
}
class HistoryFre extends Component {
  props: Props
  state: States
  getData: Function
  getChannel: Function
  channelChange: Function
  refer: Function
  websocketInit: Function
  constructor (props: Object) {
    super(props)
    this.state = {
      loading: false,
      chartData: [],
      channelData: [],
      channelIdSpeed: {},
      channelIdDeric: [],
      channelIds: []
    }
    this.getData = this.getData.bind(this)
    this.getChannel = this.getChannel.bind(this)
    this.channelChange = this.channelChange.bind(this)
    this.refer = this.refer.bind(this)
    this.websocketInit = this.websocketInit.bind(this)
  }

  componentWillMount () {
    this.getChannel() // 取通道后画图
  }

  getChannel () {
    // 通道
    const { deviceData } = this.props
    const id = deviceData.id
    universalFetch(`${__SERVICE_API__}device/devices/${id}/channel-ids`)
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        const channelData = json.result.filter((dd) => dd.sensorType === '振动量')
        const item = channelData[0].channelIds
        const keyId = item[0]['keyId']
        this.setState({
          channelData: item,
          channelIds: [keyId + '_' + item[0].id],
          channelIdDeric: [String(item[0].id)],
          channelIdSpeed: Object.assign({}, this.state.channelIdSpeed, {
            [keyId]: item[0].id
          })
        }, () => {
          this.getData(this.props)
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  channelChange (values: Array<string>) {
    let deric = []
    let speed = {}
    values.map((d, i) => {
      const s = d.split('_')
      deric.push(s[1])
      speed[s[0]] = s[1]
    })
    this.setState({
      channelIds: values,
      channelIdDeric: deric,
      channelIdSpeed: speed
    })
  }

  refer () {
    this.getData(this.props)
  }

  getData (props: Props) { // 工况实时数据通频转速
    this.setState({
      loading: true
    })
    // let indsName = ['通频值', '转速']
    const { deviceData } = props
    const { channelIdDeric, channelIdSpeed, channelData } = this.state
    const deviceNo = deviceData.deviceNo.split('_')
    let channelIdSpeedArray = []
    Object.keys(channelIdSpeed).map((d, i) => {
      channelIdSpeedArray.push(channelIdSpeed[d])
    })
    // const token = localStorage.getItem('asset_token')
    const postBody = JSON.stringify({
      fieldGroup: 'c_vib',
      fields: ['direc'],
      coValueFilter: {
        idFieldFilter: {
          factory_id: { '$eq': String(deviceNo[0]) },
          equipment_id: { '$eq': String(deviceNo[1]) },
          machine_id: { '$eq': String(deviceNo[2]) },
          datatype: { '$eq': '1' },
          '$or': channelIdDeric.map((d, i) => {
            return { 'channel_id': { '$eq': String(d) } }
          })
        }
      },
      timeRange: {
        start:'now-30m',
        end: 'now'
      },
      order: [{ '$default': 'asc' }],
      size: 30,
      page: 1
    })
    // const postBodyData = {
    //   'tsTable' : 'c_vib',
    //   // 'allCol' : 'true',
    //   'startTime' : moment().subtract(30, 'm').unix(),
    //   'endTime' : moment().unix(),
    //   'queryConditions' : [
    //     {
    //       'colName' : 'factory_id',
    //       'condition' : 'eq',
    //       'value' : String(deviceNo[0])
    //     },
    //     {
    //       'colName' : 'equipment_id',
    //       'condition' : 'eq',
    //       'value' : String(deviceNo[1])
    //     },
    //     {
    //       'colName' : 'machine_id',
    //       'condition' : 'eq',
    //       'value' : String(deviceNo[2])
    //     },
    //     {
    //       'colName' : 'datatype',
    //       'condition' : 'eq',
    //       'value' : 1
    //     },
    //     {
    //       'colName' : 'channel_id',
    //       'condition' : 'in',
    //       'value' : channelIdDeric
    //     }
    //   ],
    //   cols : ['direc']
    // }
    // const postBody = JSON.stringify(postBodyData)
    const postBody2 = JSON.stringify({
      fieldGroup: 'c_vib',
      fields: ['speed'],
      coValueFilter: {
        idFieldFilter: {
          factory_id: { '$eq': String(deviceNo[0]) },
          equipment_id: { '$eq': String(deviceNo[1]) },
          machine_id: { '$eq': String(deviceNo[2]) },
          datatype: { '$eq': '1' },
          '$or': channelIdSpeedArray.map((d, i) => {
            return { 'channel_id': { '$eq': String(d) } }
          })
        }
      },
      timeRange: {
        start:'now-30m',
        end: 'now'
      },
      order: [{ '$default': 'asc' }],
      size: 30,
      page: 1
    })
    // const postBody2Data = {
    //   'tsTable' : 'c_vib',
    //   // 'allCol' : 'true',
    //   'startTime' : moment().subtract(30, 'm').unix(),
    //   'endTime' : moment().unix(),
    //   'queryConditions' : [
    //     {
    //       'colName' : 'factory_id',
    //       'condition' : 'eq',
    //       'value' : String(deviceNo[0])
    //     },
    //     {
    //       'colName' : 'equipment_id',
    //       'condition' : 'eq',
    //       'value' : String(deviceNo[1])
    //     },
    //     {
    //       'colName' : 'machine_id',
    //       'condition' : 'eq',
    //       'value' : String(deviceNo[2])
    //     },
    //     {
    //       'colName' : 'datatype',
    //       'condition' : 'eq',
    //       'value' : 1
    //     },
    //     {
    //       'colName' : 'channel_id',
    //       'condition' : 'in',
    //       'value' : channelIdSpeedArray
    //     }
    //   ],
    //   cols : ['speed']
    // }
    // const postBody2 = JSON.stringify(postBody2Data)
    fetch(`${__KMX_REAL_TIME_API__}data-streams`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
        // 'X-Auth': token
      },
      body: postBody
    })
    .then((res) => res.json())
    .then((json) => {
      // if (json.code !== 0) {
      //   throw new Error(JSON.stringify({ code: json.code, message: json.message }))
      // }
      const results = json.results
      if (results && results.length > 0) {
        let data1 = [] // 通频值的数组
        // let data2 = [] // 转速的数组
        results.map((data, index) => {
          const channelName = channelData.filter((dd) => String(dd.id) === String(data.compoundId.channel_id))[0].name
          data['type'] = 'line'
          data['data'] = data.streams.map((d, i) => {
            return d
          })
          data['sensorNameEn'] = 'c_vib' // 用于底部事件名称点击绘图
          data['sensorName'] = '振动量' // 用于底部事件名称点击绘图
          data['channelName'] = channelName
          data['name'] = '通频值__' + channelName
          data['Title'] = '通频值'
          data1.push(data)
          // if (index % 2 === 0) {
          //   data['name'] = '通频值__' + channelName
          //   data['Title'] = '通频值'
          //   data1.push(data)
          // } else {
          //   data['name'] = '转速__' + channelName
          //   data['Title'] = '转速'
          //   data2.push(data)
          // }
        })
        fetch(`${__KMX_REAL_TIME_API__}data-streams`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
            // 'X-Auth': token
          },
          body: postBody2
        })
        .then((res) => res.json())
        .then((json) => {
          // if (json.code !== 0) {
          //   throw new Error(JSON.stringify({ code: json.code, message: json.message }))
          // }
          this.setState({
            loading: false
          })
          const results = json.results
          if (results && results.length > 0) {
            // let data1 = [] // 通频值的数组
            let data2 = [] // 转速的数组
            results.map((data, index) => {
              const channelName = channelData.filter((dd) => String(dd.id) === String(data.compoundId.channel_id))[0].name
              data['type'] = 'line'
              data['data'] = data.streams.map((d, i) => {
                return d
              })
              data['sensorNameEn'] = 'c_vib' // 用于底部事件名称点击绘图
              data['sensorName'] = '振动量' // 用于底部事件名称点击绘图
              data['channelName'] = channelName
              data['name'] = '转速__' + channelName
              data['Title'] = '转速'
              data2.push(data)
              // if (index % 2 === 0) {
              //   data['name'] = '通频值__' + channelName
              //   data['Title'] = '通频值'
              //   data1.push(data)
              // } else {
              //   data['name'] = '转速__' + channelName
              //   data['Title'] = '转速'
              //   data2.push(data)
              // }
            })
            this.setState({
              chartData: [
                data1,
                data2
              ]
            })
          } else {
            message.info('暂无数据')
            this.setState({
              loading: false,
              chartData:[]
            })
          }
        })
        .catch((error) => {
          console.error(error)
          this.setState({
            loading: false,
            chartData:[]
          })
        })
      } else {
        message.info('暂无数据')
        this.setState({
          loading: false,
          chartData:[]
        })
      }
    })
    .catch((error) => {
      console.error(error)
      this.setState({
        loading: false,
        chartData:[]
      })
    })
  }

  websocketInit (series) {
    const { deviceData } = this.props
    const { channelIdDeric } = this.state
    const deviceNo = deviceData.deviceNo.split('_')
    let postBody = {
      fieldGroup: 'c_vib',
      fields: ['direc', 'speed'],
      coValueFilter: {
        idFieldFilter: {
          factory_id: { '$eq': String(deviceNo[0]) },
          equipment_id: { '$eq': String(deviceNo[1]) },
          machine_id: { '$eq': String(deviceNo[2]) },
          datatype: { '$eq': '1' },
          '$or': channelIdDeric.map((d, i) => {
            return { 'channel_id': { '$eq': String(d) } }
          })
        }
      },
      timeRange: {
        start:'now-10m',
        end: 'now'
      },
      order: [{ '$default': 'desc' }],
      size: 1,
      page: 1
    }
    // let postBody = {
    //   'tsTable' : 'c_vib',
    //   // 'allCol' : 'true',
    //   'startTime' : moment().subtract(30, 'm').unix(),
    //   'endTime' : moment().unix(),
    //   'queryConditions' : [
    //     {
    //       'colName' : 'factory_id',
    //       'condition' : 'eq',
    //       'value' : String(deviceNo[0])
    //     },
    //     {
    //       'colName' : 'equipment_id',
    //       'condition' : 'eq',
    //       'value' : String(deviceNo[1])
    //     },
    //     {
    //       'colName' : 'machine_id',
    //       'condition' : 'eq',
    //       'value' : String(deviceNo[2])
    //     },
    //     {
    //       'colName' : 'datatype',
    //       'condition' : 'eq',
    //       'value' : 1
    //     },
    //     {
    //       'colName' : 'channel_id',
    //       'condition' : 'in',
    //       'value' : channelIdDeric
    //     }
    //   ],
    //   cols : ['direc', 'speed']
    // }
    // const token = localStorage.getItem('asset_token')
    return fetch(`${__KMX_REAL_TIME_API__}data-streams`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
        // 'X-Auth': token
      },
      body: JSON.stringify(postBody)
    }).then((res) => res.json())
    .then((jsons) => {
      const results = jsons.results
      if (results && results.length > 0) {
        series.map((d, i) => {
          const reg = results.filter((dd, ii) => {
            return dd.field === series[0].userOptions.field
          })
          if (d && reg[i]) {
            if (reg[i].streams.length > 0) {
              const streams = reg[i]['streams']
              d.addPoint(streams[0], true, true)
            }
          }
        })
      }
    })
    .catch(() => {})
  }

  render () {
    const { loading, chartData, channelIds, channelData } = this.state
    return (
      <div className={styles['main']}>

        <div className={styles['condition']}>
          <Popover content={
            <div>
              <div className={styles['conditionTop']}>
                <CheckboxGroup value={channelIds} options={
                  channelData.map((d, i) => {
                    return { label: d.name, value: String(d.keyId + '_' + d.id) }
                  })
                } onChange={this.channelChange} />
              </div>
              <p className={styles['leftFooter']}>
                <Button type='primary' onClick={this.refer} disabled={loading}>绘制</Button>
              </p>
            </div>
          } trigger='click' title='通道：'>
            <Button type='primary' className={styles['conditionBtn']}>选择指标</Button>
          </Popover>
        </div>

        <Spin spinning={loading} tip='加载中...'>
          {
            <DynamicLineLiandong
              websocketInit={this.websocketInit}
              chartData={chartData}
            />
          }
        </Spin>
      </div>
    )
  }
}

export default HistoryFre
